package com.coursehub.coursemanagement.transaction;

import com.coursehub.course.entity.Course;
import com.coursehub.course.repository.CourseRepository;
import com.coursehub.shared.transaction.AbstractTransactionStep;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 创建课程事务步骤
 * 演示如何在课程管理服务中使用分布式事务
 */
@Slf4j
public class CreateCourseTransactionStep extends AbstractTransactionStep {
    
    private final CourseRepository courseRepository;
    
    private Course createdCourse;
    private final Course courseToCreate;

    public CreateCourseTransactionStep(Course courseToCreate, CourseRepository courseRepository) {
        super("创建课程", "在课程管理服务中创建新课程");
        this.courseToCreate = courseToCreate;
        this.courseRepository = courseRepository;
    }
    
    @Override
    protected void doExecute() throws Exception {
        try {
            // 保存执行前状态
            saveExecutionState();
            
            // 执行创建课程操作
            createdCourse = courseRepository.save(courseToCreate);
            
            log.info("成功创建课程: ID={}, 名称={}", createdCourse.getCourseId(), createdCourse.getCourseName());
            
        } catch (Exception e) {
            log.error("创建课程失败: {}", e.getMessage(), e);
            throw new Exception("创建课程失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    protected void doCompensate() throws Exception {
        if (createdCourse != null && createdCourse.getCourseId() != null) {
            try {
                // 删除已创建的课程
                courseRepository.deleteById(createdCourse.getCourseId());
                log.info("成功补偿删除课程: ID={}, 名称={}", createdCourse.getCourseId(), createdCourse.getCourseName());
                
                // 清理状态
                clearExecutionState();
                
            } catch (Exception e) {
                log.error("补偿删除课程失败: ID={}, 错误: {}", createdCourse.getCourseId(), e.getMessage(), e);
                throw new Exception("补偿删除课程失败: " + e.getMessage(), e);
            }
        } else {
            log.info("无需补偿，课程未成功创建");
        }
    }
    
    @Override
    protected void saveExecutionState() {
        // 保存执行前的状态，这里可以记录一些必要的信息用于补偿
        log.debug("保存创建课程事务步骤的执行状态");
    }
    
    @Override
    protected void clearExecutionState() {
        // 清理执行状态
        createdCourse = null;
        log.debug("清理创建课程事务步骤的执行状态");
    }
    
    @Override
    public boolean canExecute() {
        // 检查是否可以执行
        return courseToCreate != null && 
               courseToCreate.getCourseName() != null && 
               !courseToCreate.getCourseName().trim().isEmpty();
    }
    
    /**
     * 获取创建的课程
     */
    public Course getCreatedCourse() {
        return createdCourse;
    }
}